package com.clg.dataSource;

import com.clg.common.constants.Constants;
import com.clg.common.jdbc.DatabaseKit;
import com.clg.common.model.DataSource;
import com.clg.common.model.DatabaseType;
import com.clg.common.tools.RetRes;
import com.jfinal.aop.Before;
import com.jfinal.kit.PathKit;
import com.jfinal.plugin.activerecord.tx.Tx;
import org.apache.log4j.Logger;

import java.net.URL;
import java.net.URLClassLoader;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * Created by usercai on 2016/10/15.
 */
@Before(Tx.class)
public class DataSourceService{
    private static Logger log = Logger.getLogger(DataSourceService.class);

    public RetRes testDataSource(String id){
        DataSource dataSource = DataSource.dao.findById(id);

        DatabaseType databaseType = DatabaseType.dao.findById(dataSource.getDataTypeId());
        Connection conn = null;
        try {
            conn = DatabaseKit.getConnection(dataSource.getJdbcUrl(),databaseType.getJdbcDriverClass(),dataSource.getLoginName(),dataSource.getPassword(), PathKit.getWebRootPath()+databaseType.getJdbcJarPath());
        } catch (Exception e) {
            log.debug(e);

            dataSource.setStatus(Constants.DATA_SOURCE_ERROR);
            dataSource.update();
            return RetRes.create(false).setMessage(e.getMessage());
        } finally {
            try {  if(conn!=null)conn.close();  } catch (SQLException e) {  }
        }

        if(conn==null){
            dataSource.setStatus(Constants.DATA_SOURCE_ERROR);
            dataSource.update();
            return RetRes.create(false).setMessage("连接失败");
        }
        dataSource.setStatus(Constants.DATA_SOURCE_SUCCESS);
        dataSource.dao.update();
        return RetRes.create(true);
    }

    public RetRes testConfigDataSource(String typeID,String jdbcUrl,String user,String pass){
        DatabaseType dataSourceType = DatabaseType.dao.findById(typeID);

        Connection conn = null;
        try {
            conn = DatabaseKit.getConnection(jdbcUrl,dataSourceType.getJdbcDriverClass(),user,pass, PathKit.getWebRootPath()+dataSourceType.getJdbcJarPath());
        } catch (Exception e) {
            log.debug(e);
            return RetRes.create(false).setMessage(e.getMessage());
        } finally {
            try {  if(conn!=null)conn.close();  } catch (SQLException e) {  }
        }

        if(conn==null){
            return RetRes.create(false).setMessage("连接失败");
        }
        return RetRes.create(true);
    }

}

